import store from "@/store";
import ElementUI from "element-ui";
import {
  Message
} from "element-ui";
import {
  debounce
} from '@/utils/tools'
import APIULR from "./baseURL";
import axios from "axios";

var instance = axios.create({
  /*   timeout: 15000, */
  baseURL: process.env.NODE_ENV === "production" ? APIULR.expert : APIULR.expert,
});

instance.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";

instance.interceptors.request.use(
  function (config) {
    if (config.requestBaseUrl) {
      config.baseURL = APIULR[config.requestBaseUrl];
    }
    let token = store.state.token;
    if (token) {
      config.headers = {
        accessToken: token,
      };
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  function (response) {
    // console.log(response, "response");
    return response.data;
  },
  function (error) {
    // console.log(error, "error");

    if (error.code == "ERR_NETWORK") {
      debounce(messageFn("网络错误", "error"), 500)
    } else if (error.code == 'ECONNABORTED') {
      debounce(messageFn("请求超时，请重试", "error"), 500)
    }
    switch (error.response.status) {
      case 400:
        messageFn(error.response.data.message, "error");
        break;
      case 403:
        messageFn("资源不可用！", "error");
        break;
      case 404:
        messageFn("资源未找到！", "error");
        break;
      default:
        return Promise.reject(error);
    }
  }
);

function messageFn(msg, type) {
  /* 
   type: 'success'
   type: 'warning'
   type: 'error'
  */
  ElementUI.Message({
    showClose: true,
    message: msg,
    type: type,
    center: true,
  });
}

export default instance;
